'use strict';

const Controller = require('egg').Controller;

class BaseController extends Controller {

	// 返回用户信息
	async returnMsg(code = 1, msg = 'OK', data = false) {

		var returnMsg = {};
		returnMsg.code = code;
		returnMsg.msg = msg;
		if(data || data === 0) {
			returnMsg.data = data;
		}

		return returnMsg;
	}

	// 获取用户信息（包含验证）
	async getCustomInfo() {

		const {
			ctx
		} = this;

		const requestObj = ctx.request.body;

		if (!requestObj.hasOwnProperty("payKey")){
			ctx.body = await this.returnMsg(0, '请求非法，缺少用户key');
			return false;
		}
		if (!requestObj.hasOwnProperty("sign")){
			ctx.body = await this.returnMsg(0, '请求非法，缺少签名');
			return false;
		}
		const pcKey = requestObj.payKey;
		if (!pcKey){
			ctx.body = await this.returnMsg(0, '请求非法，用户key无效');
			return false;
		}

		const userInfo = await ctx.service.customer.getInfoKey(pcKey);

		if(!userInfo) {
			ctx.body = await this.returnMsg(0, '请求非法，用户key无效');
			return false;
		}

		const ip = ctx.request.ip;
		const isIpPass = await this.checkIp(userInfo.pcId, ip);
		if(!isIpPass) {
			ctx.body = await this.returnMsg(0, '请求非法，请求ip无效');
			return false;
		}
		
		if(userInfo.pcEnable === 0) {
			ctx.body = await this.returnMsg(0, '该商户尚未审核通过');
			return false;
		}
		
		if(userInfo.pcEnable === -1) {
			ctx.body = await this.returnMsg(0, '该商户已被冻结');
			return false;
		}
		
		var checkSign = await this.createTkSign(requestObj, userInfo.pcSignCode);
//		console.log('checkSign:' + checkSign);
		if (checkSign != requestObj.sign){
//			ctx.body = await this.returnMsg(0, '请求签名错误');
//			return false;
		}
		
		userInfo.pcPayConfig = JSON.parse(userInfo.pcPayConfig);
		
		return userInfo;
	}

	// 校验ip
	async checkIp(pcId, reqIp) {

		const ipList = await this.app.mysql.select('pay_ip', {
			where: {
				pcId: pcId,
				piType: "white"
			}
		});

		var pass = false;
		for(var i = 0; i < ipList.length; i++) {
			if(ipList[i].piIp == reqIp || ipList[i].piIp == '*') {
				pass = true;
				break;
			}
		}
		return pass;
	}

	// 添加请求日志
	async addReqLog() {

		const ctx = this.ctx;
		const reqUrl = ctx.request.origin + ctx.request.url;
		const reqData = ctx.request.body;
		const ip = ctx.request.ip;

		return await ctx.service.common.addReqLog(ip, reqUrl, reqData);
	}

	// 更新请求日志结果
	async setReqLog(prlId, rtnData) {
		const ctx = this.ctx;
		return await ctx.service.common.setReqLog(prlId, rtnData);
	}
	
	// 签名
	async createTkSign(paramJson, secretStr) {
		const ctx = this.ctx;
		return await ctx.service.common.createTkSign(paramJson, secretStr);
	}
}

module.exports = BaseController;